/* File: fractals.c
 * --------------------
 * Author: Albin Olausson & Stella Wallin
 * Last modified: 2014-04-15
 * Task: A recursive program that creates
 * fractals inside of a triangle.
 */

#include <stdio.h>
#include "graphics.h"
#include "math.h"

/* typedef pointT */

typedef struct{
	double x;
	double y;
}pointT;

/* Prototypes */

void createTriangle(int order, pointT p1, pointT p2, pointT p3);
pointT findMiddle(pointT p1, pointT p2);

/* Main program */

main(){
	int order = 3;
	pointT p1, p2, p3;
	InitGraphics();

	printf("Program by S. Wallin & A. Olausson.\n\n");
	p1.x = 0; p1.y = 0;
	p3.x = 5; p3.y = 0;
	p2.x = (p3.x - p1.x) / 2; p2.y = 3;

	createTriangle(order, p1, p2, p3);
} 

/*
 * Function: createTriangle
 * Usage: void createTriangle(order-1, p4, p5, p6); 
 * -------------------------------
 * A recursive function that creates points for 
 * the fractals. On the way up from the recursion it 
 * draw the lines between them, creating the fractal triangles.
 */

void createTriangle(int order, pointT p1, pointT p2, pointT p3){
	pointT tmp, p4, p5, p6;
	
	if(order != 0){
		p4 = findMiddle(p1,p2);
		p5 = findMiddle(p2,p3);
		p6 = findMiddle(p3,p1);
		createTriangle(order-1, p4, p5, p6);
		createTriangle(order-1, p1, p4, p6);
		createTriangle(order-1, p6, p5, p3);
		createTriangle(order-1, p4, p2, p5);
	}

	MovePen(p1.x, p1.y);
	DrawLine(p2.x - p1.x, p2.y-p1.y);
	DrawLine(p3.x - p2.x, p3.y-p2.y);
	DrawLine(p1.x - p3.x, p1.y-p3.y);
}	

/*
 * Function: findMiddle
 * Usage: p4 = findMiddle(p1,p2);
 * -------------------------------
 * A function that saves a point halfway
 * between two points and determines were the new 
 * point should be. 
 */

pointT findMiddle(pointT p1, pointT p2){
	pointT newPoint;

	newPoint.x = (p1.x + p2.x) / 2;
	newPoint.y = (p1.y + p2.y) / 2;

	return newPoint;
}